// 文件: Archer.ts (增大攻击范围后的版本)
import { _decorator, Component, Node, Prefab, instantiate, Vec3, find, tween, Tween } from 'cc';
import { EnemyMovement } from './EnemyMovement';
import { Arrow } from './Arrow';
import { GameManager } from './GameManager';
import { GameView } from './game/gameView/GameView';
import { UserData } from './UserData';

const { ccclass, property } = _decorator;

@ccclass('Archer')
export class Archer extends Component {
    @property({ type: Prefab, tooltip: "箭矢的预制体" })
    private arrowPrefab: Prefab = null;

    // ===================================================================
    // 【【【 在这里修改攻击范围 】】】
    // 我已经将默认值从 1500 增加到了 2500，这对于大多数竖屏游戏来说都足够了。
    // 如果你觉得还不够，可以把这个数字改得更大，比如 3000。
    // ===================================================================
    @property({ tooltip: "弓箭手的攻击范围（半径）" })
    private attackRange: number = 100000;

    @property({ tooltip: "攻击速度（秒/次）" })
    private attackInterval: number = 1.5;

    public get AttackInterval(): number {
        return this.attackInterval - this.attackInterval * UserData.AttackScale;
    }

    @property({ type: Node, tooltip: "箭矢发射点" })
    private firePoint: Node = null;

    @property
    private attackDamage: number = 11111; // 每箭造成的伤害

    private target: Node = null;
    private attackTimer: number = 0;

    private shootTween: Tween = null;

    update(dt: number) {
        if (!this.target || !this.target.isValid || this.isTargetOutOfRange()) {
            this.findNewTarget();
        }

        if (this.target) {
            this.attackTimer += dt;
            if (this.attackTimer >= this.AttackInterval) {
                this.attackTimer = 0;
                this.fireArrow();
            }
        }
    }

    private findNewTarget() {
        const enemies = GameManager.Instance.allEnemies;
        let closestEnemy: Node = null;
        let minDistance = this.attackRange;

        for (const enemyScript of enemies) {
            const enemyNode = enemyScript.node;
            if (enemyNode && enemyNode.isValid) {
                const distance = Vec3.distance(this.node.worldPosition, enemyNode.worldPosition);
                if (distance < minDistance) {
                    minDistance = distance;
                    closestEnemy = enemyNode;
                }
            }
        }

        this.target = closestEnemy;
    }

    private isTargetOutOfRange(): boolean {
        if (!this.target) return true;
        const distance = Vec3.distance(this.node.worldPosition, this.target.worldPosition);
        return distance > this.attackRange;
    }

    private fireArrow() {
        if (!this.arrowPrefab || !this.target) return;

        const trajectory: number = UserData.Trajectory - 1;
        const interval: number = this.AttackInterval / 4;
        let dt: number = 0;
        if (trajectory > 0) {
            dt = interval / UserData.Trajectory;
        }

        if (dt <= 0) {
            this.shootArrow();
        } else {
            let index: number = 1;
            this.shootArrow();

            this.shootTween = tween(this.firePoint)
                .delay(dt)
                .call(() => {
                    this.shootArrow();
                    index++;

                    if (index >= UserData.Trajectory) {
                        this.shootTween.stop();
                        this.shootTween = null;
                    }
                })
                .union()
                .repeatForever()
                .start();
        }
    }

    private shootArrow() {
        const arrowNode = instantiate(this.arrowPrefab);
        GameView.Instance.node.addChild(arrowNode);

        const fireWorldPos = this.firePoint ? this.firePoint.worldPosition : this.node.worldPosition;
        arrowNode.setWorldPosition(fireWorldPos);

        const arrowScript = arrowNode.getComponent(Arrow);
        if (arrowScript) {
            arrowScript.setTarget(this.target, this.attackDamage);
        }
    }
}
